package com.yenlien.traceyun.usercenter.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yenlien.traceyun.usercenter.bean.CustomAppView;
import com.yenlien.traceyun.usercenter.dao.*;
import com.yenlien.traceyun.usercenter.entity.*;
import com.yenlien.traceyun.usercenter.service.AppService;
import com.yenlien.traceyun.webase.controller.BaseController;
import com.yenlien.traceyun.webase.utils.CheckParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Sort;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author: bigwangy@sina.com
 * @create: 2020-07-21
 * @description:
 **/

@RestController
@RequestMapping(value = "/app")
public class AppController extends BaseController {

    @Autowired
    private AppDao appDao;

    @Autowired
    private CustomAppDao customAppDao;

    @Autowired
    private CustomAppVersionDao customAppVersionDao;


    @Autowired
    private AppService appService;

    @Autowired
    private CompanyCustomAppVersionDao companyCustomAppVersionDao;

    @Autowired
    private CompanyDao companyDao;


    /**
     * app注册功能
     *
     * @param param
     * @return
     */
    @RequestMapping(value = "/register")
    public Object register(@RequestBody JSONObject param) {
        Optional<App> optional = appDao.findById(param.getString("appId"));
        if (optional.isPresent()) {
            App app = optional.get();
            app.setType(param.getString("appType"));
            app.setName(param.getString("appName"));
            app.setCode(param.getString("appCode"));
            appDao.save(app);
            return app;
        } else {
            App app = new App();
            app.setId(param.getString("appId"));
            app.setType(param.getString("appType"));
            app.setName(param.getString("appName"));
            app.setCode(param.getString("appCode"));
            app.setCreatetime(new Date());
            app.setUsed(true);
            appDao.save(app);
            return app;
        }
    }

    /**
     * 加载所有产品
     *
     * @return
     */
    @GetMapping(value = "/list")
    public Object list() {
        return success(appDao.findAll());
    }

    @GetMapping(value = "/appIdlist")
    public JSONArray AppIdList() {
        List<App> all = appDao.findAll();
        JSONArray array = new JSONArray();
        for (App app : all) {
            JSONObject obj = new JSONObject();
            List<Company> companies = companyDao.companyfindByAppId(app.getId());
            obj.put("appInfo", app);
            obj.put("companyList", companies);
            array.add(obj);
        }
        return array;
    }

    @PostMapping(value = "/used")
    public Object used(@RequestBody JSONObject params) {
        CheckParams.checkJson(params, new String[]{"id", "used"});
        appDao.used(params.getString("id"), params.getBoolean("used"));
        return success("ok");
    }

    /**
     * 所有自定义产品下拉
     *
     * @return
     */
    @PostMapping(value = "/customApp/findAll")
    public Object findAllCustomApp(@RequestBody CustomApp customApp) {
        return success(customAppDao.findAll());
    }

    /**
     * 所有自定义产品列表
     *
     * @return
     */
    @PostMapping(value = "/list/customapp")
    public Object findCustomApp(@RequestBody CustomApp customApp) {
        Page<CustomApp> page = appService.findByList(customApp);
        List<CustomAppView> views = CustomAppView.create(page.getContent());
        Set<String> ids = views.stream().map(p -> p.getId()).collect(Collectors.toSet());
        if (ids != null && ids.size() > 0) {
            List<CustomAppVersion> versions = customAppVersionDao.findByCustomAppIdIn(ids);
            if (versions != null && versions.size() > 0) {
                for (CustomAppView view : views) {
                    for (CustomAppVersion customAppVersion : versions) {
                        if (view.getId().equals(customAppVersion.getCustomAppId())) {
                            view.getVersions().add(customAppVersion);
                        }
                    }
                }
            }
        }
        JSONObject result = new JSONObject();
        result.put("code", "200");
        result.put("total", page.getTotalElements());
        result.put("rows", views);
        return result;
    }

    /**
     * 创建自定义app应用
     *
     * @param customApp
     * @param request
     * @return
     */
    @PostMapping(value = "/create/customapp")
    public Object createCustomApp(CustomApp customApp, HttpServletRequest request) throws Exception {
        List<MultipartFile> files = null;
        if (!StringUtils.isEmpty(((MultipartHttpServletRequest) request).getFile("files"))) {
            files = ((MultipartHttpServletRequest) request).getFiles("files");
        }
        return success(appService.createCustomApp(customApp, files));
    }

    @PostMapping(value = "/create/customapp2")
    public Object createCustomApp2(@RequestBody CustomApp customApp) throws Exception {
        return success(appService.createCustomApp2(customApp));
    }

    /**
     * 修改自定义app应用
     *
     * @param customApp
     * @param request
     * @return
     */
    @PostMapping(value = "/update/customapp")
    public Object updateCustomApp(CustomApp customApp, HttpServletRequest request) throws Exception {
        List<MultipartFile> files = null;
        if (!StringUtils.isEmpty(((MultipartHttpServletRequest) request).getFile("files"))) {
            files = ((MultipartHttpServletRequest) request).getFiles("files");
        }
        return success(appService.updateCustomApp(customApp, files));
    }

    /**
     * 修改自定义app应用
     *
     * @return
     */
    @GetMapping(value = "/listall/customapp")
    public Object listCustomApp() throws Exception {
        return success(customAppDao.findAll(Sort.by(Sort.Direction.DESC, "createTime")));
    }

    /**
     * 添加自定义app应用
     *
     * @param params
     * @param request
     * @return
     */
    @PostMapping(value = "/create/customappversion")
    public Object createCustomappversion(@RequestBody JSONObject params, HttpServletRequest request) {
        CustomAppVersion customAppVersion = params.getJSONObject("customAppVersion").toJavaObject(CustomAppVersion.class);
        List<String> ids = params.getJSONArray("ids").toJavaList(String.class);


        return success(appService.createCustomAppVersion(customAppVersion, ids));
    }

    /**
     * 根据自定义customappid，查询版本
     *
     * @param customappid
     * @return
     */
    @GetMapping(value = "/list/customappversion/{customappid}")
    public Object findCustomAppVersion(@PathVariable("customappid") String customappid) {
        return success(customAppVersionDao.findByCustomAppId(customappid));
    }

    /**
     * 根据自定义版本Id查询自定义产品
     *
     * @param id
     * @return
     */
    @GetMapping(value = "/findCustomAppVersionId/{id}")
    public Object findCustomAppVersionId(@PathVariable("id") String id) {
        return success(appService.findCustomAppVersionId(id));
    }

    /**
     * 根据公司id和APPID查询自定义产品
     *
     * @param jsonObject
     * @return
     */
    @PostMapping(value = "/findCompanyCustomAppVersion")
    public Object findCompanyCustomAppVersion(@RequestBody CompanyCustomAppVersion jsonObject) {
        CheckParams.checkBean(jsonObject, new String[]{"companyId", "appId"});
        return success(appService.findByModelIds(jsonObject.getCompanyId(), jsonObject.getAppId()));
    }


    /**
     * 根据公司id查询自定义产品
     *
     * @return
     */
    @GetMapping(value = "/loadbycompanyId/{id}")
    public Object loadbycompanyId(@PathVariable("id") String id) {
        return success(companyCustomAppVersionDao.findByCompanyId(id));
    }

    @GetMapping(value = "/getCustomAppVersion/{companyId}")
    public Object getCustomAppVersion(@PathVariable("companyId") String companyId) {
        return success(customAppVersionDao.getCustomAppVersion(companyId));
    }

    @GetMapping(value = "/getCompanyCustomAppVersion/{companyId}")
    public Object getCompanyCustomAppVersion(@PathVariable("companyId") String companyId) {
        return success(companyCustomAppVersionDao.findByParentId(companyId));
    }


}
